package com.base.cn.platform.os.service.op.giftcard;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.dao.op.giftcard.OpGiftCardDao;
import com.base.cn.platform.os.entity.op.giftcard.OpGiftCard;
import com.base.cn.platform.os.entity.op.giftcard.OpGiftCardCode;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 推荐数据表
 * Created by ll on 2018/05/14.
 */
@Service
@Slf4j
public class OpGiftCardBiz extends BaseBiz<OpGiftCard,OpGiftCardDao>{
    @Autowired
    private OpGiftCardCodeBiz opGiftCardCodeBiz;
    @Autowired
    private CourseService courseService;

    /**
     * 搜索礼品卡
     * @param page 分页
     * @param giftCard  礼品卡
     * @return
     */
    public PageInfo<OpGiftCard> queryGiftCardListPage(Pagination page, OpGiftCard giftCard,boolean courseData){
        String  whereSql = this.whereGiftCardSql(giftCard);
        PageInfo<OpGiftCard> pageInfo =this.findPage(whereSql,page,null);
        if (courseData){
            pageInfo.setList(setCourseByGiftCordList(pageInfo.getList()));
        }
        return pageInfo;
    }
    /**
     * 保存礼品卡
     * @param giftCard
     * @return
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public OpGiftCard tx_saveGiftCard(OpGiftCard giftCard){
        giftCard.setStatus(0);
        this.save(giftCard);
        this.generateGiftCardCode(giftCard);
        return giftCard;
    }


    /**
     * 条件搜索语句
     * @param giftCard
     * @return
     */
    public String  whereGiftCardSql(OpGiftCard giftCard){
        StringBuilder whereSql = new StringBuilder(" 1 = 1");
        if(giftCard.getCardType()!=null && giftCard.getCardType()>0){
            whereSql .append(" and cardType=").append(giftCard.getCardType());
        }
        if(StringUtils.isNotEmpty(giftCard.getCardName())){
            whereSql .append(" and cardName like concat ('%','").append(giftCard.getCardName()).append("','%')");
        }
        if(ObjectUtils.isNotEmpty(giftCard.getIsExchange())){
            whereSql .append(" and isExchange  = ").append(giftCard.getIsExchange());
            whereSql .append(" and (integralGoodId is null  or integralGoodId='' or integralGoodId=0) ");
        }
        if(StringUtils.isNotEmpty(giftCard.getDepict())){
            whereSql .append(" and depict like concat ('%','").append(giftCard.getDepict()).append("','%')");
        }
        if(StringUtils.isNotEmpty(giftCard.getCourseIds())){
            whereSql .append( " and courseIds like concat ('%','").append(giftCard.getCourseIds()).append("','%')");
        }
        if(giftCard.getTimeType()!=null && giftCard.getTimeType()>0){
            whereSql .append( " and timeType = ").append(giftCard.getTimeType());
        }
        if(giftCard.getBeginTime()!=null){
            whereSql .append( " and createTime >= '" ).append(new SimpleDateFormat("yyyy-MM-dd").format(giftCard.getBeginTime())).append(" 00:00:00'");
        }
        if(giftCard.getEndTime()!=null){
            whereSql .append( " and endTime <= '").append( new SimpleDateFormat("yyyy-MM-dd").format(giftCard.getEndTime())).append(" 23:59:59'");
        }
        if(giftCard.getStatus()!=null){
            whereSql .append( " and status =").append(giftCard.getStatus());
        }else{
            whereSql .append( " and status !=3");
        }
        whereSql .append( " order by id desc");
        return whereSql.toString();
    }

    /**
     * 搜索礼品卡Ids
     * @param giftCardIds
     * @return
     */
    public List<OpGiftCard> queryOpGiftCardListByIds(String giftCardIds,boolean courseData){
        List<OpGiftCard> cards =this.find(" id in ("+giftCardIds+")",null,null);
        if (courseData){
            cards = setCourseByGiftCordList(cards);
        }
        return cards;
    }

    /**
     * 搜索礼品卡Id
     * @param giftCardId
     * @return
     */
    public OpGiftCard queryOpGiftCardById(BigDecimal giftCardId,boolean courseData){
        List<OpGiftCard> opGiftCards = this.queryOpGiftCardListByIds(giftCardId+"",courseData);
        if (ObjectUtils.isNotEmpty(opGiftCards)&&courseData){
            opGiftCards = setCourseByGiftCordList(opGiftCards);
            return opGiftCards.get(0);
        }
        return null;
    }


    /**
     * 批量冻结，删除，恢复
     * @param giftCardIds
     * @param status
     */
    public void  updateStatusByIds(String giftCardIds,Integer status){
        List<OpGiftCard> giftCards = queryOpGiftCardListByIds(giftCardIds,false);
        List<OpGiftCard> giftCardList =new ArrayList<>();
        String  _giftCardIds = "";
        for(OpGiftCard giftCard :giftCards){
            if(giftCard.getStatus()==0&&status==3){
                _giftCardIds+=giftCard.getId()+",";
            }else{
                OpGiftCard giftCard1 = new OpGiftCard();
                giftCard1.setId(giftCard.getId());
                giftCard1.setTimeType(giftCard.getTimeType());
                giftCard1.setCourseIds(giftCard.getCourseIds());
                giftCard1.setDepict(giftCard.getDepict());
                giftCard1.setStatus(status);
                giftCardList.add(giftCard1);
            }
        }
        if(StringUtils.isNotEmpty(_giftCardIds)){
            _giftCardIds=_giftCardIds.substring(0,_giftCardIds.length()-1);
            this.deleteWhereSql("id in("+_giftCardIds+")");
            opGiftCardCodeBiz.deleteWhereSql(" giftCardId in ("+giftCardIds+")");

        }else {
            this.updateBatch(giftCardList);
            OpGiftCardCode giftCardCode =new OpGiftCardCode();
            giftCardCode.setStatus(status);
            opGiftCardCodeBiz.updateByWhereSql(giftCardCode," giftCardId in ("+giftCardIds+")");
        }

    }


    /**
     * 生成礼品卡编码
     * @param giftCard 礼品卡
     */
    public void generateGiftCardCode(OpGiftCard giftCard)  {
        long _time1 = System.currentTimeMillis();
        //如果未生成优惠券编码
        int genNum = giftCard.getGenNum();
        List<OpGiftCardCode> giftCardCodes = new LinkedList<>();
        for (int j = 0; j < genNum; j++) {
            String code = StringUtils.handleStrValue(DateUtils.format(new Date(),"yyyyMMddHHmmssSSS") + j).substring(0, 20); //优惠券编码
            OpGiftCardCode giftCardCode = new OpGiftCardCode();
            giftCardCode.setGiftCardId(giftCard.getId());
            giftCardCode.setCardType(giftCard.getCardType());
            giftCardCode.setTimeType(giftCard.getTimeType());
            giftCardCode.setIsExchange(giftCard.getIsExchange());
            if(giftCard.getTimeType()==1){
                giftCardCode.setBeginTime(giftCard.getBeginTime());
                giftCardCode.setEndTime(giftCard.getEndTime());
            }else{
                giftCardCode.setTimeDays(giftCard.getTimeDays());
            }
            giftCardCode.setUseType(1);
            giftCardCode.setCode(code);
            giftCardCode.setCodePwd(StringUtils.getRandStr(10));
            giftCardCode.setStatus(1);
            giftCardCodes.add(giftCardCode);
        }
        long _time2 = System.currentTimeMillis();
        log.info("--------------- h1 : "+((_time2-_time1)/1000L) +"秒");

        long _time3 = System.currentTimeMillis();
        opGiftCardCodeBiz.batchSave(giftCardCodes);
        long _time4 = System.currentTimeMillis();
        log.info("--------------- h2 : "+((_time4-_time3)/1000L) +"秒");
    }



    /**
     * 赠送礼品卡
     * @return
     */
    public void presentGiftCard(List<OpGiftCardCode> opGiftCardCodes){
        opGiftCardCodeBiz.updateBatch(opGiftCardCodes);
    }

    /**
     * 积分兑换商品
     * @param userId
     * @param giftCardId
     * @return
     */
    public Map<String,Object> exchangeGiftCard(BigDecimal userId,
                                             BigDecimal giftCardId){

        List<OpGiftCardCode> giftCardCodes = opGiftCardCodeBiz.queryOpGiftCardCodesByGiftCardIdAndStatusAndIsUserData(giftCardId,1,null,1);
        if (!ObjectUtils.isNotEmpty(giftCardCodes)) {
            return ResultUtil.ERROR("商品库存不足");
        }
        if(ObjectUtils.isNotEmpty(giftCardCodes)){

                if(giftCardCodes.get(0).getTimeType()==2){
                    Date date = new Date();
                    Date endTime = DateUtils.addByDate(date, Calendar.DAY_OF_MONTH,giftCardCodes.get(0).getTimeDays());
                    giftCardCodes.get(0).setBeginTime(date);
                    giftCardCodes.get(0).setEndTime(endTime);
                }
                giftCardCodes.get(0).setUserId(userId);

        }
        this.presentGiftCard(giftCardCodes);
        return ResultUtil.SUCCESS("礼品卡赠送成功",giftCardCodes.get(0).getId());
    }



    /**
     * 添加课程List
     * @param giftCordList
     * @return
     */
    public List<OpGiftCard> setCourseByGiftCordList(List<OpGiftCard> giftCordList){
        if(ObjectUtils.isNotEmpty(giftCordList)){
            String courseIds = "";
            for(OpGiftCard giftCard :giftCordList){ courseIds+=giftCard.getCourseIds()+",";}
            if(StringUtils.isNotEmpty(courseIds)){
                String[] courseId = courseIds.split(",");
                String _courseIds ="";
                for(int i=0;i<courseId.length;i++){
                    if(StringUtils.isNotEmpty(courseId[i])&&
                            !courseId[i].equals("null")&&
                            Long.parseLong(courseId[i])>0){
                        _courseIds+=courseId[i]+",";
                    }
                }
                if (StringUtils.isNotEmpty(_courseIds)){
                    _courseIds=_courseIds.substring(0,_courseIds.length()-1);
                    Map<BigDecimal,Map<String,Object>> courseMap = courseService.findCourseToMapByIds(_courseIds,false,false,false);
                    for (OpGiftCard giftCard:giftCordList){
                        List<Map<String,Object>> courseList = new ArrayList<>();
                        List<BigDecimal> cids= new ArrayList<>(courseMap.keySet());
                        for(BigDecimal l:cids){
                            if (ObjectUtils.isNotEmpty(giftCard.getCourseIds())){
                                if(giftCard.getCourseIds().contains(","+l+",")){
                                    courseList.add(courseMap.get(l));
                                }
                            }
                        }
                        giftCard.setCourseList(courseList);
                    }
                }
            }
        }
        return giftCordList;
    }


    /**
     * 添加课程
     * @param giftCord
     * @return
     */
    public OpGiftCard setCourseByGiftCord(OpGiftCard giftCord){
        List<OpGiftCard> opGiftCards = new ArrayList<>();
        opGiftCards.add(giftCord);
        opGiftCards =setCourseByGiftCordList(opGiftCards);
        return opGiftCards.get(0);
    }
}
